<template>
  <v-layout row wrap>
    <v-flex xs12 sm12 md10 offset-md1>
      <v-card>
        <v-card-title>
          <span class="headline">新建</span>
        </v-card-title>
        <v-card-text>
          <v-container grid-list-md >
            <v-layout wrap>
              <v-flex xs12 sm12 md12>
                <v-text-field label="选项" v-model="option.option"></v-text-field>
              </v-flex>
              <v-flex xs12 sm12 md12>
                <v-text-field label="缩略图" v-model="option.thumbnail"></v-text-field>
                <v-data-table
                  v-if="files"
                  :items="files"
                  class="elevation-1"
                  hide-actions
                  hide-headers
                >
                  <template slot="items" slot-scope="props">
                    <td class="text-xs-left">{{ props.item.name }}</td>
                    <td class="text-xs-left">{{ props.item.size | formatSize }}</td>
                    <td class="text-xs-right" v-if="props.item.error">{{file.error}}</td>
                    <td class="text-xs-right" v-else-if="props.item.success">success</td>
                    <td class="text-xs-right" v-else-if="props.item.active">active</td>
                    <td class="text-xs-right" v-else></td>
                  </template>
                </v-data-table>
                <file-upload
                  type="button"
                  class="btn primary"
                  :post-action="uploadAction"
                  :headers="headers"
                  extensions="gif,jpg,jpeg,png,webp"
                  accept="image/png,image/gif,image/jpeg,image/webp"
                  :multiple="false"
                  :size="1024 * 1024 * 10"
                  v-model="files"
                  @input-filter="inputFilter"
                  @input-file="inputFile"
                  ref="upload">
                  <div class="btn__content">
                    选择文件
                  </div>
                </file-upload>
                <v-btn color="success" v-if="!$refs.upload || !$refs.upload.active" @click.prevent="$refs.upload.active = true">
                  开始上传
                </v-btn>
                <v-btn color="danger"  v-else @click.prevent="$refs.upload.active = false">
                  停止上传
                </v-btn>
              </v-flex>
              <v-flex xs12 sm12 md12>
                <label>描述</label>
                <quill-editor v-model="option.description"
                              ref="myQuillEditor"
                              :options="editorOption"
                              @change="onEditorChange($event)">
                </quill-editor>
              </v-flex>
              <v-flex xs12 sm12 md12>
                <v-text-field label="参加人数" v-model="option.vote_count"></v-text-field>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click.native="close">取消</v-btn>
          <v-btn color="blue darken-1" flat @click.native="save">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-flex>
  </v-layout>
</template>
<script>
import axios from '@/helpers/http'
import jwtToken from '@/helpers/jwt'
import FileUpload from 'vue-upload-component'

import {quillEditor, Quill} from 'vue-quill-editor'
import {container, ImageExtend, QuillWatch} from 'quill-image-extend-module'

Quill.register('modules/ImageExtend', ImageExtend)

export default {
  components: {
    FileUpload,
    quillEditor
  },

  data () {
    return {
      files: [],
      uploadAction: 'http://vote.test/api/v2/upload',
      headers: {
        Authorization: 'Bearer ' + jwtToken.getToken()
      },
      option: {
        option: '',
        thumbnail: '',
        description: '',
        vote_count: 0
      },
      editorOption: {
        modules: {
          ImageExtend: {
            loading: true,
            name: 'file',
            action: 'http://vote.test/api/v2/upload',
            headers: (xhr) => {
              xhr.setRequestHeader('Authorization', 'Bearer ' + jwtToken.getToken())
            },
            response: (response) => {
              return response.data
            }
          },
          toolbar: {
            container: container,
            handlers: {
              'image': function () {
                QuillWatch.emit(this.quill.id)
              }
            }
          }
        }
      }
    }
  },
  methods: {
    inputFilter (newFile, oldFile, prevent) {
      if (newFile && !oldFile) {
        // Before adding a file
        // 添加文件前
        // Filter system files or hide files
        // 过滤系统文件 和隐藏文件
        if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
          return prevent()
        }
        // Filter php html js file
        // 过滤 php html js 文件
        if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
          return prevent()
        }
      }
    },
    inputFile (newFile, oldFile) {
      if (newFile.success) {
        this.option.thumbnail = newFile.response.data
      }
    },

    onEditorChange ({ quill, html, text }) {
      this.option.description = html
    },
    close () {
      this.$router.go(-1)
    },
    save () {
      let formData = {
        option: this.option.option,
        thumbnail: this.option.thumbnail,
        description: this.option.description,
        vote_count: this.option.vote_count
      }
      return axios.post('/api/v2/votes/' + this.$route.params.vote + '/options', formData).then(response => {
        this.$router.push({name: 'options.index', params: {vote: this.$route.params.vote}})
      }).catch(error => {
        if (error.response.status === 400) {
          this.$store.dispatch('showNotification', { 'level': 'error', 'msg': '选项添加错误', 'alert': true })
        }
      })
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  }
}
</script>
